<template>
  <div>
    <basic-dialog :visible="show"
                  title="驱动配置"
                  :isShowClose="true"
                  :is-show-basic-footer="false"
                  min-width="800px"
                  @close="show = false"
    >
      <q-form @submit="submit" class="q-gutter-md dialog-content" ref="myForm" style="height: 567px">
        <div class="container">
          <div>
            <div class="driver-title"  v-if="isCnc">设备信息</div>
            <fuzzy-search
              v-model.trim="queryParams.device"
              :isShowValue="false"
              showAllOption
              isForm
              smallSize
              v-if="isCnc"
              title="关联设备"
              style="width: 440px"
              :rules="[val => val !== null || '请选择关联设备']"
              :options="deviceListAll"
              :fuzzyFunc="getFilter"
            ></fuzzy-search>

            <div class="flex"  v-if="isCnc">
              <yz-input v-model="queryParams.partcountType"
                        inputType="select"
                        :rules="[0]"
                        :options="partcountType"
                        title="清零/累加"
                        style="width: 440px"
              />
              <span>
              <q-icon name="iconfont icontubiao-72" class="text-grey" style="margin-left: 5px;margin-top: 10px;font-size: 14px" />
              <q-tooltip max-width="500px">
                <div>例如: 本次采集的计数值为30，上次采集的计数值为500。当选择累加，则认为此段时间的产量为530；当选择清零，则认为此段时间的仍为500</div>
              </q-tooltip>
            </span>
            </div>

            <div class="driver-title">驱动信息</div>
            <yz-input v-model="queryParams.driver"
                      inputType="select"
                      class="content-width"
                      :rules="[0]"
                      :options="driverList"
                      title="选择驱动"
            />
            <div v-if="queryParams.driver" class="driver-detail content-width margin-b-20">
              <div class="flex justify-between">
                <div>
                  <div>控制器类型: {{driverDetail[0]}}</div>
                  <div>控制器型号: {{driverDetail[2]}}</div>
                  <div>IOT接口: {{driverDetail[4]}}</div>
                </div>
                <div>
                  <div>控制器品牌: {{driverDetail[1]}}</div>
                  <div>协议名称: {{driverDetail[3]}}</div>
                </div>
              </div>
              <div>驱动描述: {{ driverDescription }}</div>
            </div>

            <yz-input v-model="queryParams.version"
                      inputType="select"
                      class="content-width"
                      :rules="[0]"
                      :options="versionListAll"
                      title="选择版本"
            />
          </div>
        </div>
        <q-separator />
        <div class="dialog-footer text-center margin-t-10">
          <q-btn outline label="取消" color="primary" @click="hideDialog" class="q-mr-md"/>
          <q-btn unelevated label="下一步" color="primary" type="submit" :loading="submitting"/>
        </div>
      </q-form>
    </basic-dialog>
  </div>
</template>
<script>
import { allDriverBind } from '../../../../../boot/miot/plc-list'
import { getDeviceCNC } from '../../../../../boot/miot/list'
import { partcountType } from '../plc-dialog/constant'

export default {
  name: 'driver-dialog',
  props: {
    driverParams: {
      type: Object,
      default: () => {}
    },
    controllerType: {
      type: String,
      default: ''
    },
    driverListAll: {
      type: Array,
      default: () => []
    },
    productsCnc: {
      type: Array,
      default: () => []
    },
    driverDeviceObj: {
      type: Object,
      default: () => {}
    },
    isPreVersion: {
      type: Boolean,
      default: false
    },
    updateVersion: {
      type: [String, Number],
      default: ''
    },
    boxRemark: {
      type: [String, Number],
      default: ''
    }
  },
  data () {
    return {
      partcountType,
      show: false,
      submitting: false,
      queryParams: {
        driver: '',
        version: '',
        device: '',
        partcountType: '1'
      },
      boxDriverId: '',
      subDeviceSn: '',
      subDeviceId: '',
      currentDriverData: null,
      deviceList: []
    }
  },
  computed: {
    versionListAll () {
      if (this.queryParams.driver) {
        return this.driverInfo[this.queryParams.driver] || []
      }
      return []
    },
    // 根据选择的driver获取详情
    driverDetail () {
      if (this.driverList.length > 0) {
        const info = this.driverList.find(item => item.value === this.queryParams.driver)
        return info?.label.split('_') || []
      }
      return []
    },
    driverDescription () {
      if (this.driverList.length > 0 && this.queryParams.driver) {
        return this.driverList.find(item => item.value === this.queryParams.driver)?.description || '--'
      }
      return '--'
    },
    driverList () {
      const controllerObj = {
        '0': 'CNC',
        '1': 'PLC',
        '2': 'PLC'
      }
      const result = [...this.driverListAll]
      if (this.currentDriverData) {
        result.unshift(this.currentDriverData)
      }
      return result.filter(item => item.label.startsWith(controllerObj[this.controllerType]))
    },
    driverInfo () {
      const obj = {}
      this.driverList.forEach(item => {
        obj[item.value] = item?.versionList?.map(v => ({
          label: v.version,
          value: v.version
        }))
      })
      return obj
    },
    isCnc () {
      return this.controllerType + '' === '0'
    },
    deviceListAll () {
      if (this.driverDeviceObj?.value) {
        const index = this.deviceList.findIndex(item => item.value === this.driverDeviceObj.value)
        if (index === -1) {
          return [this.driverDeviceObj, ...this.deviceList]
        }
      }
      return this.deviceList
    }
  },
  watch: {
    'queryParams.driver': {
      handler: function () {
        this.queryParams.version = this.versionListAll[0]?.value || ''
      }
    }
  },
  methods: {
    showDialog (info, currentDriverData, device, partcountType) {
      // 初始化参数
      this.subDeviceSn = ''
      this.boxDriverId = ''
      this.subDeviceId = ''
      this.currentDriverData = null
      Object.assign(this.queryParams, this.$options.data.call(this).queryParams)
      // 如果为编辑
      if (info) {
        this.subDeviceSn = info.subDeviceSn
        this.boxDriverId = info.id
        this.subDeviceId = info.subDeviceId
        this.queryParams.driver = info.driverId
        this.queryParams.partcountType = partcountType + '' || '1'
        this.$nextTick(() => {
          this.queryParams.version = info.driverVersion
        })
      }
      if (currentDriverData) {
        this.currentDriverData = currentDriverData
      }
      if (this.isCnc) {
        this.getDeviceList()
        if (device) {
          this.queryParams.device = device
        }
      }
      this.show = true
    },
    hideDialog () {
      this.show = false
    },
    // 提交驱动
    submit () {
      this.submitLatest()
    },
    submitLatest () {
      const driverItem = this.driverList.find(item => item.value === this.queryParams.driver)
      const deviceItem = this.deviceListAll.find(item => item.value === this.queryParams.device)
      const data = {
        'gatewayId': this.driverParams.gatewayId,
        'driverId': this.queryParams?.driver,
        'driverName': driverItem?.label,
        'version': this.queryParams?.version,
        'productId': this.driverParams.productId,
        'boxNum': this.driverParams.boxNum,
        'ucloudBoxNum': this.driverParams.ucloudBoxNum,
        'gateWayType': this.controllerType,
        'updateVersion': this.updateVersion
      }
      if (this.isPreVersion) {
        data.subDeviceId = this.subDeviceId || this.driverParams.subDeviceId
      }
      if (this.subDeviceSn) {
        data.subDeviceSn = this.subDeviceSn
        data.boxDriverId = this.boxDriverId
        data.subDeviceId = this.subDeviceId
      }
      if (this.isCnc) {
        data.deviceNum = this.queryParams.device
        data.deviceId = deviceItem?.id
        data.partcountType = this.queryParams.partcountType
        if (this.boxRemark + '' !== '3') {
          const cncModelItem = this.productsCnc.find(item => item.name === 'CNC_Model')
          if (!cncModelItem) {
            this.$message.error('机床物模型不存在 无法创建')
            return
          }
          data.hwProductId = cncModelItem.product_id
        }
      }
      this.submitting = true
      allDriverBind(data).then(res => {
        this.$emit('successSubmit', res.data)
      }).finally(() => {
        this.submitting = false
      })
    },
    // 获取设备列表
    async getDeviceList () {
      const { data } = await getDeviceCNC()
      this.deviceList = data.map(item => {
        return {
          label: `${item.device_name}(${item.device_num})`,
          value: item.device_num,
          id: item.id
        }
      })
    },
    getFilter (val) {
      return new Promise(resolve => {
        const res = {
          code: '1200',
          data: [],
          message: ''
        }
        if (val) {
          setTimeout(() => {
            res.data = this.deviceListAll.filter(item => {
              return item.label.toLowerCase().indexOf(val.toLowerCase()) > -1
            })
            resolve(res)
          }, 200)
        } else {
          setTimeout(() => {
            res.data = this.deviceListAll
            resolve(res)
          }, 200)
        }
      })
    }
  }
}

</script>

<style scoped lang="scss">
.driver-title{
  line-height: 1;
  font-size: 18px;
  font-weight: 500;
  color: #5f77fd;
  margin: 24px 0;
}
.content-width{
  width: 440px;
}
.container{
  height: 515px;
  //width: 800px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;

  .driver-detail{
    padding: 0 30px;
    font-size: 16px;
    line-height: 2;
  }
}

</style>
